package leetcode.leetcode_637;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> doubles = new ArrayList<>();
        if (root == null) {
            return doubles;
        }
        LinkedList<TreeNode> nodes = new LinkedList<>();
        nodes.add(root);
        while (!nodes.isEmpty()) {
            int size = nodes.size();
            double sum =0;
            for (int i =0 ;i<size;i++){
                TreeNode poll = nodes.poll();
                sum+= poll.val;
                if (poll.left != null) {
                    nodes.add(poll.left);
                }
                if (poll.right != null) {
                    nodes.add(poll.right);
                }
            }
            doubles.add(sum/size);
        }
        return doubles;

    }
}